package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("/*")    //所有访问资源都被拦截
public class LoginFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void  doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //判断访问资源路径是否和登录注册相关
        //1,在数组中存储登陆和注册相关的资源路径

        String[] loginUrls = {
                "/employee/login",
                "/employee/logout",
                "/user/login",
                "/user/sendMsg",
                "/backend/**",
                "/front/**"};

        //获取访问资源的路径
        String requestURI = request.getRequestURI();

        log.info("登录过滤器:" + requestURI);
        //判断是否放行
        boolean flag = checkUrl(loginUrls, requestURI);
        if (flag) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }

        //判断管理端用户是否登录过，登录过session存入了用户id
        if (request.getSession().getAttribute("employee") != null) {
            //通过ThreadLocal获取Session中的id
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            Long sessionId = BaseContext.getCurrentId();
            filterChain.doFilter(request, response);
            return;
        }

        //判断前台用户是否登录过，登录过session存入了用户id
        if (request.getSession().getAttribute("user") != null) {
            //通过ThreadLocal获取Session中的id
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("user"));
            Long sessionId = BaseContext.getCurrentId();
            filterChain.doFilter(request, response);
            return;
        }

        //未登录成功
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void destroy() {
    }


    /**
     * 路径匹配，检查本次请求是否需要放行
     */
    public boolean checkUrl(String[] urls, String requestUrl) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestUrl);
            if (match) {
                return true;
            }
        }
        return false;
    }

}
